﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using HZ.Supervise.Model;
using HZ.Supervise.Model.Enum;
using HZ.Supervise.IBLL;

namespace HZ.Supervise.Web.Admin
{
    public partial class UserOperateBatch : BasePage
    {
        IBLL_User iu = BLLFactory.BLL_User();
        IBLL_Role ir = BLLFactory.IBLL_Role();
        KeyOperationLogJG kj; 
        DataTable _roleOperateTable;

        public UserOperateBatch()
        {
            //this.ModuleNo = Module.主用户管理.ToString();
            //this.PageOperateType = OperateType.权限设置.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string userIds = Request.QueryString["uids"];
            string roleId = Request.QueryString["rid"];
            string roleName = Request.QueryString["rname"];
            if (!this.IsPostBack)
            {
                //
                ViewState["v_uids"] = userIds;
                ViewState["v_rid"] = roleId;


                if (!string.IsNullOrEmpty(userIds) && !string.IsNullOrEmpty(roleId))
                {
                    lblUserId.Text = userIds;
                    lblRoleName.Text = roleName;

                    //用户所在角色的操作权限
                    IList<OperatingRule> roleOperateList = ir.GetRoleOperatingRuleByRoleID(roleId);

                    //转换成DataTable
                    _roleOperateTable = HZ.Data.ModelConvert.GetDataTableFromModel(roleOperateList);

                    //分组以获得模块列表
                    DataTable tableModule = _roleOperateTable.DefaultView.ToTable(true, "Module");
                    //添加模块枚举值列
                    tableModule.Columns.Add(new DataColumn("ModuleValue", typeof(System.Int32)));
                    foreach (DataRow row in tableModule.Rows)
                    {
                        row["ModuleValue"] = EnumParse.GetModule((int)row["Module"]);
                    }
                    //按模块枚举值排序
                    DataView dv = new DataView(tableModule);
                    dv.Sort = "ModuleValue asc";


                    this.rptModule.DataSource = dv;
                    this.rptModule.DataBind();
                }
                else
                {
                    PageError("用户不存在", "UserList.aspx");
                }
            }
        }

        /// <summary>
        /// 绑定rptOperate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptModule_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataTable table;

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                table = this._roleOperateTable;
                if (table.Rows.Count > 0)
                {
                    DataView dv = new DataView(table);
                    dv.RowFilter = "Module ='" + DataBinder.Eval(e.Item.DataItem, "Module").ToString() + "'";
                    //dv.Sort = " OperatingRuleName";
                    Repeater rptStoreSubject = (Repeater)e.Item.FindControl("rptOperate");
                    rptStoreSubject.DataSource = dv;
                    rptStoreSubject.DataBind();
                }
            }
        }

        /// <summary>
        /// 保存设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            int count = 0;
            int errorCount = 0;
            string strSucessUserIds = "";
            string strErrorUserIds = "";
            string userIds = ViewState["v_uids"].ToString();

            //构造权限集合
            List<OperatingRule> operatingRuleList = new List<OperatingRule>();
            string ids = Request["chkOperate"];
            if (!string.IsNullOrEmpty(ids))
            {
                string[] arraryIds = ids.Split(',');
                foreach (string Item in arraryIds)
                {
                    OperatingRule otr = new OperatingRule();
                    otr.OperatingRuleID = Item;
                    operatingRuleList.Add(otr);
                }
            }

            //复选框选中，设置角色中所有用户
            if (this.cbAllUser.Checked)
            {
                IBLL_User iu = BLLFactory.BLL_User();
                int TotalCount = 0;
                IList<HZ.Supervise.Model.View.OrgUsers> listUser = iu.GetOrgUsersByWhere(new HZ.Supervise.Model.Query.OrgUsers() { IsAdmin=true, RoleID = Convert.ToString(ViewState["v_rid"]) }, 1, 0, out TotalCount);
                //置空用户IDs字符串
                userIds = "";
                foreach (var item in listUser)
                {
                    userIds += item.UserID + ",";
                }
                userIds = userIds.TrimEnd(',');
            }

            //循环保存
            string[] arrayUids = userIds.Split(',');
            foreach (string Item in arrayUids)
            {
                if (iu.SetUserOperatingRule(Item, operatingRuleList))
                {
                    count++;
                    strSucessUserIds += Item + ",";
                    AddLog(string.Format("批量设置用户[{0}]权限成功!",  strSucessUserIds));
                }
                else
                {
                    errorCount++;
                    strErrorUserIds += Item + ",";
                }
            }

            string strMessage = "权限更新成功执行！结果如下：\n\n";
            strMessage += "成功的用户：共 " + count + " 个。\n";
            strMessage += "失败的用户：共 " + errorCount + " 个" + ((errorCount != 0) ? "；用户ID：" + strErrorUserIds.TrimEnd(',') : "") + "。"; ;
            //显示结果
            PageInfo(strMessage, this.ReturnUrl);


        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="msg"></param>
        private void AddLog(string msg)
        {
            kj = new KeyOperationLogJG();
            kj.OperationLogSerialID = Guid.NewGuid().ToString();
            kj.Operator = CurrentAccount.GetUser().UserID;
            kj.OrgID = CurrentAccount.GetUser().Org.OrgID;
            kj.OperateTime = DateTime.Now;
            kj.OperateMessage = msg;
            iu.AddKeyOperationLog(kj);
        }
    }
}
